<?php

namespace backend\models;

use Yii;
use backend\base\BaseModel;

class AdminRolePermissionModel extends BaseModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'role_permission';
    }

    public function rules()
    {
        return [
            [['id','role_id','create_time'], 'integer', 'message' => '{attribute}必须整数'],
            [['permission_codes'], 'string'],
            [['role_id','permission_codes'], 'required', 'on' => ['add','edit'], 'message' => '{attribute}不能为空'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'role_id' => '角色ID',
            'permission_codes' => '权限codes',
            'create_time' => '创建时间',
        ];
    }

    /**
     * 保存前
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert)
    {
        if(parent::beforeSave($insert)){
            if($this->isNewRecord){
                $this->create_time = time();
                $this->status = 1;
            }
            return true;
        }
        return false;
    }

    /**
     * 角色是否有权限
     * @param $role_id
     * @param $url
     * @return bool
     */
    public static function checkAuth($role_id,$code)
    {
        //检查角色
        $role = AdminRoleModel::findOne($role_id);
        if(!$role || $role->status != 0){
            return false;
        }
        //检查权限
        $permission = self::find()->where("(permission_codes like $code)")->andWhere(['role_id'=>$role_id])->one();
        if($permission){
            return true;
        }
        return false;
    }


    /*
     * 获取对应角色权限列表
     * @param int $role_id
     * @return array
     */
    public static function getRolePermissionList($role_id=0)
    {
        $permission_res = PermissionModel::levelList();
        $role_permission = self::getPermissionIds($role_id);
        $role_permission = !empty($role_permission) ? explode(',',$role_permission['permission_codes']) : [];
        $permission_res = self::reset($role_permission,$permission_res);
        return $permission_res;
    }

    //无限极
    public static function reset($res,$list)
    {
        if ($list) {
            foreach ($list as $k => $val) {
                $list[$k]['active'] = 0;
                if(in_array($val['menu_code'],$res)){
                    $list[$k]['active'] = 1;
                }
                if(isset($val['btn_code']) && in_array($val['btn_code'],$res)){
                    $list[$k]['active'] = 1;
                }
                if(!empty($val['child'])) {
                    $list[$k]['child'] = self::reset($res, $val['child']);
                }
            }
        }
        return $list;
    }

    /*
     * 保存权限
     * @param $role_id
     * @param $permission_ids
     */
    public static function updatePermission($role_id,$permission_ids)
    {
        //权限id列表
        $role_permission = self::getPermissionIds($role_id);
        //需要删除的差集
        $del_diff = array_diff($role_permission,$permission_ids);
        //需要新增的差集
        $add_diff = array_diff($permission_ids,$role_permission);
        if($del_diff || $add_diff){
            $tr = Yii::$app->db->beginTransaction();
            if($del_diff){
                $res = self::deleteAll('role_id = '.$role_id.' and permission_id in('.implode(',',$del_diff).')');
                if(!$res){
                    $tr->rollBack();
                    return false;
                }
            }
            if($add_diff){
                $data = [];
                $time = time();
                foreach($add_diff as $val){
                    $data[]=[$role_id,$val,$time];
                }
                $res = Yii::$app->db->createCommand()->batchInsert(self::tableName(), ['role_id','permission_id','create_time'], $data)->execute();
                if(!$res){
                    $tr->rollBack();
                    return false;
                }
            }
            $tr->commit();
        }
        return true;
    }

    /**
     * 权限角色id获取权限id列表
     * @param $role_id
     * @return array
     */
    public static function getPermissionIds($role_id)
    {
        return self::find()->select('permission_codes')->where('role_id='.(int)$role_id)->asArray()->one();
    }

}